<template>
  <el-dialog
    v-el-drag-dialog
    title="本地打印设置"
    :visible.sync="visible"
    width="700px"
    append-to-body
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp">
      <el-form-item label="本地打印地址:" prop="url" class="block">
        <el-input v-model="temp.url" style="width: 500px;">
          <el-button
            slot="append"
            class="append-search"
            :loading="$loadingPlugin.tryConnect"
            @click="tryConnect"
          >尝试连接</el-button>
        </el-input>
      </el-form-item>
      <el-form-item class="block">
        <div>
          <span
            style="display: inline-block; width: 525px;"
          >下拉不出打印机列表请点击重新加载</span>
          <el-button type="primary" @click="loadPrinters">重新加载</el-button>
        </div>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      highlight-current-row
      :column="tableData.column"
      :data="tableData.data"
      :total="tableData.total"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 关闭 </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
// import { JCJSONTools, tryConnection } from '@/utils/JCCache'
// import printJson from './printJson.json'
  import { getPrinterSetting } from '@/api'
  // import { mapActions, mapMutations } from 'vuex'
  import JCPrint from './printer'
  export default {
    name: 'printSetting',
    data() {
      return {
        visible: false,
        // jCPrint: null,
        time: 0,
        temp: {
          url: ''
        },
        rules: {
          url: [{ required: true, message: '请输入IP及端口号', trigger: 'blur' }]
        },
        printList: [],
        tableData: {
          total: 0,
          column: [
            {
              label: '模板名称',
              prop: 'templateType',
              width: '',
              //
              render: (h, { row, $index, column }) => {
                return <div>{this.nameFotmatter(row.templateType)}</div>
              }
            },
            {
              label: '打印机',
              prop: 'printer',
              width: '',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      size='mini'
                      value={scope.row[scope.column.property]}
                      onInput={(val) => {
                        scope.row[scope.column.property] = val
                      }}
                    >
                      {' '}
                    </el-input>
                  ) : (
                    <span>
                      {scope.row[scope.column.property]
                        ? scope.row[scope.column.property]
                        : ''}
                    </span>
                  )}
                </div>
                )
              }
            },
            {
              label: '左偏移',
              prop: 'left',
              width: 100,
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input
                      size='mini'
                      value={row[column.property]}
                      onInput={(val) => {
                        this.changeInput(row, column, val)
                      }}
                    >
                      {' '}
                    </el-input>
                  ) : (
                    <span>{row[column.property] ? row[column.property] * 1 : ''}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '上偏移',
              prop: 'top',
              width: 100,
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input
                      size='mini'
                      value={row[column.property]}
                      onInput={(val) => {
                        this.changeInput(row, column, val)
                      }}
                    >
                      {' '}
                    </el-input>
                  ) : (
                    <span>{row[column.property] ? row[column.property] * 1 : ''}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '份数',
              prop: 'count',
              width: 100,
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input
                      size='mini'
                      value={row[column.property]}
                      onInput={(val) => {
                        this.changeInput(row, column, val)
                      }}
                    >
                      {' '}
                    </el-input>
                  ) : (
                    <span>{row[column.property] ? row[column.property] * 1 : ''}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '操作',
              align: 'center',
              // fixed: 'right',
              width: 80,
              render: (h, { row, $index }) => {
                return (
                <div>
                  <el-link
                    underline={false}
                    size='mini'
                    onClick={() => this.handleEdit(row)}
                  >
                    {row._edit ? '' : '编辑'}
                  </el-link>
                  <el-link
                    underline={false}
                    size='mini'
                    onClick={() => this.handleSave(row)}
                  >
                    {row._edit ? '保存' : ''}
                  </el-link>
                </div>
                )
              }
            }
          ],
          data: [{ count: 1 }]
        }
      }
    },
    created() {
      // window.tools = {
      //   json: new JCJSONTools()
      // }
      this.initLink()
    },
    methods: {
      initLink() {
        if (!localStorage.printerUrl) {
          this.temp.url = '127.0.0.1:10001'
        } else {
          this.temp.url = localStorage.printerUrl
        }

        if (this.temp.url === '') {
          return
        }

        this.jCPrint = new JCPrint('wjh', this)
        window.jCPrint = this.jCPrint
        this.tryConnect()
        this.loadPrinters()
      },

      open() {
        return new Promise(async(resolve) => {
          if (!localStorage.printerUrl) {
            this.temp.url = '127.0.0.1:10001'
          } else {
            this.temp.url = localStorage.printerUrl
          }
          this.resolve = resolve
          this.visible = true
          // await this.PrinterType()
          this.initTable()
          this.jCPrint = new JCPrint('wjh', this)
          window.jCPrint = this.jCPrint
        })
      },
      // 连接
      conn() {
        var url = this.temp.url
        if (url === '') {
          this.$message.warning('请输入IP及端口号')
          return
        }
        this.jCPrint.setURL(url)
        this.jCPrint.tryConnection()
      },
      // 尝试连接
      tryConnect() {
        var time = this.time
        if (!time) {
          this.conn()
          this.time = 1
        } else {
          this.jCPrint.unConnection()
          return
        }
        setTimeout(() => {
          this.time = 0
        }, 500)
      },
      // 重新加载
      loadPrinters() {
        // var _this = this
        this.initTable()
        // this.jCPrint.registListener(function(msg) {
        //   // _this.printList = eval(msg)
        //   // _this.initGrid()
        //   // _this.grid.datagrid('loadData', _this.grid.datagrid('getData'))
        //   this.initTable()
        // })
        this.jCPrint.send(JSON.stringify({ cmd: 1 }))
      },

      async initTable() {
        const rlt = await getPrinterSetting()
        if (rlt.exc != null) {
          this.$message.error('查询异常')
          return
        } else if (!rlt.data) {
          this.$message.error('没有查询到相关数据')
          return
        }
        var tp
        if (!localStorage.tp) {
          tp = {}
          localStorage.setItem('tp', JSON.stringify(tp))
        } else {
          tp = JSON.parse(localStorage.tp)
        // tp = eval('(' + JSON.parse(localStorage.tp) + ')')
        }
        var list = [...rlt.data]
        var arr = []
        for (var i in list) {
          var item = list[i]

          if (item.templateContent && item.templateContent.length > 0) {
            var cc = item.templateContent
            // eval('var temp =' + cc)
            var temp = cc
            item.top = temp.top || 0
            item.left = temp.left || 0
            item.count = temp.count || 1
            item.printer = ''
            if (tp && tp[item.templateType]) {
              item = { ...item, ...tp[item.templateType] }
            }
            arr.push(item)
          }
        }
        this.tableData.data = [...arr]
      },
      nameFotmatter(val) {
        if (val === 1) {
          return '配送单'
        } else if (val === 2) {
          return '瓶批销售单'
        } else if (val === 3) {
          return '槽批销售单'
        } else if (val === 4) {
          return '押金单'
        } else if (val === 11) {
          return '调拨单'
        } else if (val === 18) {
          return '报修单'
        } else if (val === 15) {
          return '押金'
        } else if (val === 19) {
          return '回收单'
        } else if (val === 20) {
          return '装卸车单'
        } else if (val === 31) {
          return '退户申请单'
        } else if (val === 32) {
          return '退瓶单'
        } else if (val === 33) {
          return '退瓶退款单'
        } else if (val === 34) {
          return '费用办理单'
        } else if (val === 35) {
          return '气瓶提取单'
        } else if (val === 36) {
          return '瓶批销售单-新版'
        } else if (val === 37) {
          return '槽批销售单-新版'
        } else if (val === 38) {
          return '配送单-新版'
        } else if (val === 39) {
          return '订单回单'
        } else if (val === 40) {
          return '充装单'
        } else if (val === 41) {
          return '充装单(无金额)'
        } else if (val === 42) {
          return '预付卡充值'
        } else if (val === 43) {
          return '预付卡销卡'
        }
        return ''
      },
      success() {
        this.$refs.dataForm.validate((valid) => {
          if (!valid) return
          this.submit()
        })
      },

      async submit() {
        var url = this.temp.url
        if (url === '') {
          return
        }
        var tp
        if (!tp) {
          tp = {}
        } else {
          tp = JSON.parse(tp)
        }
        localStorage.printerUrl = url
        // this.acceptGoods()
        var rows = this.tableData.data
        for (var i in rows) {
          var item = rows[i]
          if (!item.printer) {
            continue
          }

          var ct = item.templateContent
          if (item.templateContent[item.templateContent.length - 1] === ';') {
            ct = ct.substring(0, item.templateContent.length - 1)
          }
          ct = Function('"use strict";return (' + ct + ')')()
          // ct = eval('(' + ct + ')')

          if (!ct) {
            continue
          }

          var temp = {}
          // $.extend(temp, ct)
          temp = { ...temp, ...ct }
          temp.top = item.top || 0
          temp.left = item.left || 0
          temp.count = item.count || 1
          temp.printer = item.printer || 'PDF'
          tp[item.templateType] = temp
        // item.items.forEach((v) => {
        //   if (v.eval) {
        //     // ct = eval('(' + ct + ')')
        //     v.eval = Function('"use strict";return (' + v.eval + ")")();
        //     console.log(v.eval);
        //   }
        // });
        }
        // $dlh.cache.setPrintTPCache($dlh.tools.json.toJson(tp))

        localStorage.tp = JSON.stringify(tp)
        this.visible = false
        // await roleUpdate(this.temp)
        // this.resolve(this.temp)
        // this.visible = false
        this.$notify({
          title: '提示',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      },
      async PrinterType() {
      // const res = await getPrinterType()
      },
      reset() {
        this.temp = {
          url: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      changeInput(row, column, value) {
        row[column.property] = this.onlyNumber(value)
      },
      onlyNumber(num) {
        var n = String(num)
        var t = n.charAt(0)
        // 先把非数字的都替换掉，除了数字和.
        n = n.replace(/[^\d\.]/g, '')
        // 必须保证第一个为数字而不是.
        n = n.replace(/^\./g, '')
        // 保证只有出现一个.而没有多个.
        n = n.replace(/\.{2,}/g, '.')
        // 保证.只出现一次，而不能出现两次以上
        n = n.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        // 如果第一位是负号，则允许添加
        if (t === '-') {
          n = '-' + n
        }
        return n
      },
      handleSave(row, $index) {
        this.$set(row, '_edit', false)
        this.$set(this.tableData.data, $index, JSON.parse(JSON.stringify(row)))
        localStorage.printerUrl = this.temp.url
      },
      handleEdit(row, $index) {
        this.$set(row, '_edit', true)
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
